<route lang="jsonc" type="page">
{
  "layout": "default",
  "style": {
    "navigationBarTitleText": "库存入库"
  }
}
</route>

<script lang="ts" setup>
import type { ResMaterialVO } from '@/api/wms/MaterialsManagement/resmaterial'
import type { RackLocationVO } from '@/api/wms/WarehouseManagement/RackLocation/index'
import { log } from 'node:console'
import { onLoad } from '@dcloudio/uni-app'
import { reactive, ref } from 'vue'
import { useMessage, useToast } from 'wot-design-uni'
import { ResInventoryApi } from '@/api/wms/MaterialsManagement/resinventory'
import { ResInventoryInApi } from '@/api/wms/MaterialsManagement/resinventoryin'
import { ResMaterialApi } from '@/api/wms/MaterialsManagement/resmaterial'
import { ResMaterialCategoryApi } from '@/api/wms/MaterialsManagement/resmaterialcategory'
import { SupplierApi } from '@/api/wms/ResourceReserves/supplier'
import { RackLocationApi } from '@/api/wms/WarehouseManagement/RackLocation/index'
import { WarehouseRackApi } from '@/api/wms/WarehouseManagement/WarehouseRack/index'
import { parseTimeToTimestamp, timestampToString } from '@/utils/date'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { showToastAsync } from '@/utils/toast'

const toast = useToast()
const message = useMessage()

const qualityStatusOptions = ref([]) // 质检状态选项
const materialList = ref<ResMaterialVO[]>([]) // 物资列表
const materialCategoryList = ref<any[]>([]) // 物资分类列表

const warehouseListSource = ref<any[]>([]) // 来源仓库列表
const warehouseRackListSource = ref<RackLocationVO[]>([]) // 来源货架列表
const rackLocationListSource = ref<any[]>([]) // 来源库位列表

const warehouseListTarget = ref<any[]>([]) // 去向仓库列表
const warehouseRackListTarget = ref<RackLocationVO[]>([]) // 去向货架列表
const rackLocationListTarget = ref<any[]>([]) // 去向库位列表
const supplierList = ref<any[]>([]) // 供应商列表
const detailId = ref(null) // 物资id
const formData = ref<any>({
})
const formRules: any = reactive({
  emergencyEvent: { required: true, message: '应急事件名称不能为空' },
  warehouseId: { required: true, message: '目标仓库不能为空' },
  rackId: { required: true, message: '目标区域不能为空' },
  quantity: { required: true, message: '入库数量不能为空' },
  inTime: { required: false, message: '入库时间不能为空' },

})
onLoad(async (options) => {
  if (options?.id) {
    detailId.value = Number(options.id)
    qualityStatusOptions.value = getIntDictOptions(DICT_TYPE.WMS_MATERIALS_RESINVENTORYOUT_STATUS)
    try {
      const [warehouseRes, rackRes, locationRes, materialRes, supplierRes, materialCategoryRes] = await Promise.all([
        WarehouseRackApi.getWarehouseList(),
        RackLocationApi.getWarehouseRackList(),
        RackLocationApi.getRackLocationList(),
        ResMaterialApi.getResMaterialList(),
        SupplierApi.getSupplierList(),
        ResMaterialCategoryApi.getResMaterialCategoryList(),
      ])
      console.log('获取物资分类列表:', materialCategoryRes)
      supplierList.value = supplierRes.data as any[]
      materialList.value = materialRes.data as any[]
      materialCategoryList.value = materialCategoryRes.data as any[]

      warehouseListSource.value = warehouseRes.data as any[]
      warehouseRackListSource.value = rackRes.data as any[]
      rackLocationListSource.value = locationRes.data as any[]

      warehouseListTarget.value = warehouseRes.data as any[]
      warehouseRackListTarget.value = rackRes.data as any[]
      rackLocationListTarget.value = locationRes.data as any[]

      const res = await ResMaterialApi.getResMaterial(detailId.value) as any
      const data = res.data as any
      console.log('获取物资详情:', data)
      formData.value = data
      // const { locationId, ...rest } = data
      // formData.value = {
      //   ...rest,
      //   locationCodeId: locationId, // 重命名字段
      // }
      console.log('formData.value ', formData.value)
    }
    catch (error) {
      console.error('解析扫码信息失败', error)
    }
  }

  console.log('✅ 页面 onLoad 执行了', options)
})
const formRef = ref(null)
/** 日期选择器默认值 */
const defaulTimetValue = ref<number>(Date.now())
// 仓库变动，清空下级并重新请求货架
async function handleWarehouseChange(warehouseId: any) {
  console.log('warehouseId', warehouseId)

  formData.value.rackId = undefined
  formData.value.locationId = undefined
  const data = await RackLocationApi.getWarehouseRackList(warehouseId.value)
  warehouseRackListTarget.value = data.data as RackLocationVO[]
  rackLocationListTarget.value = [] // 清空货位
}

// 货架变动，清空下级并重新请求货位
async function handleRackChange(rackId: any) {
  formData.value.locationId = undefined
  const data = await RackLocationApi.getRackLocationList(rackId.value)
  rackLocationListTarget.value = data.data as RackLocationVO[]

  formData.value.locationId = rackLocationListTarget.value[0].id // 货位默认为第一个
}
/** 提交表单 */
async function submitForm() {
  try {
    // 校验表单
    if (!formRef.value)
      return
    // 校验表单
    const { valid, errors } = await formRef.value.validate()
    if (!valid) {
      console.log('表单校验未通过:', errors)

      return // ✅ 校验失败，终止后续代码
    }

    uni.showLoading({
      // 正确：用${}包裹三元表达式，动态切换标题
      title: `${detailId.value ? '编辑中...' : '新增中...'}`,
      mask: true,
    })
    // if (formData.value.actualDate) {
    //   formData.value.actualDate = timestampToString(formData.value.actualDate)
    // }
    // if (formData.value.productionDate) {
    //   formData.value.productionDate = timestampToString(formData.value.productionDate)
    // }

    const resInventoryInDetails = [{
      materialId: formData.value.id,
      supplierId: formData.value.supplierId,
      actualQuantity: formData.value.actualQuantity || formData.value.quantity,
      productionDate: formData.value.productionDate,
      unitPrice: formData.value.unitPrice,
    }]
    // 构造最终要传给后端的主表对象（如果有主表字段）
    const { id, ...restFormData } = formData.value
    const payload = {
      ...restFormData,
      locationId: 14,
      resInventoryInDetails,
    }

    console.log('提交的表单数据:', payload)
    const res = await ResInventoryInApi.createResInventoryIn(payload)
    if (res.code === 0) {
      await showToastAsync('入库成功')
      setTimeout(() => {
      // 成功后跳转
        uni.switchTab({ url: '/pages/inventory/index' })
      }, 1500)
    }
  }
  catch (error) {
    console.error('表单提交失败:', error)
    toast.error('提交失败，请稍后再试')
  }
  finally {
    // ✅ 第五步：无论成功/失败，关闭加载提示（必须执行）
    uni.hideLoading()
  }
}
/** 取消表单 */
async function cancelForm() {
  try {
    // 删除的二次确认
    await message.confirm({
      msg: '您确定要取消吗？',
      title: '提示', // 添加标题
    })
    uni.navigateTo({ url: '/pages/inventory/create' })
    // 显示成功提示
    toast.success('取消成功')
  }
  catch (error) {
    console.log('用户取消了操作或发生错误:', error)
  }
}
</script>

<template>
  <view class="">
    <wd-form ref="formRef" :model="formData" :rules="formRules">
      <wd-cell-group border>
        <wd-card type="rectangle">
          <template #title>
            <view class="" style="display: flex;">
              <!-- <up-avatar src="/src/static/images/approvalForm.png" shape="square" /> -->
              <span style="display: flex;align-items: center;margin-left: 10px;">物资信息</span>
            </view>
          </template>
          <view class="">
            <!-- 动态生成输入项 -->

            <!-- <wd-input
              v-model="formData.inOrderNo"
              label="入库单号" label-width="150px"
              prop="item.inOrderNo" placeholder="请输入入库单号"
              disabled
            /> -->
            <!-- <wd-select-picker
              v-model="formData.areaCode" label="所在仓库"
              label-width="150px" prop="formData.areaCode" :columns="warehouseListSource" placeholder="请选择所在仓库" value-key="id"
              label-key="wareName" type="radio" readonly
            />
            <wd-select-picker
              v-model="formData.shelfCode" label="所在货架" label-width="150px" prop="formData.shelfCode"
              :columns="warehouseRackListSource" placeholder="请选择所在货架" value-key="id" label-key="rackName" type="radio"
              readonly filterable
            />
            <wd-select-picker
              v-model="formData.locationCodeId" label="所在库位" label-width="150px" prop="formData.locationCodeId"
              :columns="rackLocationListSource" placeholder="请选择所在库位" value-key="id" label-key="locationCode" type="radio"
              readonly filterable
            />
            <wd-select-picker
              v-model="formData.inStatus" label="是否为前置物资" label-width="150px" prop="inStatus"
              :columns="[{ label: 'Y', value: 'Y' }, { label: 'N', value: 'N' }]" placeholder="请选择是否为前置物资"
              value-key="value" label-key="label" type="radio" filterable :show-confirm="false"
            /> -->
            <wd-input
              v-model="formData.materialName" label="物资名称" label-width="150px" prop="materialName"
              placeholder="请输入物资名称" readonly
            />
            <!-- <wd-select-picker
              v-model="formData.materialId" label="物资名称" label-width="150px" prop="formData.materialId"
              :columns="materialList" placeholder="请选择物资名称" value-key="id" label-key="materialName" type="radio"
              filterable :show-confirm="false"
            /> -->
            <wd-input
              v-model="formData.materialCode" label="物资编码" label-width="150px" prop="materialCode"
              placeholder="请输入物资编码" readonly
            />
            <wd-select-picker
              v-model="formData.categoryId" label="物资分类" label-width="150px" prop="categoryId"
              :columns="materialCategoryList" placeholder="请选择物资分类" value-key="id" label-key="categoryName" type="radio" readonly
              filterable :show-confirm="false"
            />
            <wd-input
              v-model="formData.specs" label="规格型号" label-width="150px" prop="item.specs"
              placeholder="请输入规格型号" readonly
            />
            <wd-input
              v-model="formData.shelfLifeDays" label="保质期(天)" label-width="150px" prop="shelfLifeDays"
              placeholder="请输入保质期(天)" readonly
            />
            <wd-select-picker
              v-model="formData.supplierId" label="供应商名称" label-width="150px" prop="supplierId"
              :columns="supplierList" placeholder="请选择供应商名称" value-key="id" label-key="supplierName" type="radio"
              filterable :show-confirm="false" readonly
            />

            <!-- <wd-input
              v-model="formData.quantity" label="库存数量" label-width="150px" prop="item.quantity"
              placeholder="请输入库存数量" readonly
            /> -->

            <!-- <wd-datetime-picker
              v-model="formData.expiryDate" label="过期日期" type="datetime"
              placeholder="选择过期日期" label-width="150px" :default-value="defaulTimetValue" :min-date="new Date(1900, 0, 1).getTime()"
              prop="formData.expiryDate"
              readonly
            /> -->
          </view>
        </wd-card>
        <wd-card type="rectangle">
          <template #title>
            <view class="" style="display: flex;">
              <!-- <up-avatar src="/src/static/images/approvalForm.png" shape="square" /> -->
              <span style="display: flex;align-items: center;margin-left: 10px;">表单信息</span>
            </view>
          </template>
          <view class="">
            <wd-input
              v-model="formData.emergencyEvent" label="应急事件名称" label-width="150px" prop="item.emergencyEvent"
              placeholder="请输入应急事件名称"
            />
            <wd-select-picker
              v-model="formData.warehouseId" label="目标仓库"
              label-width="150px" prop="formData.warehouseId" :columns="warehouseListTarget" placeholder="请选择目标仓库" value-key="id" label-key="wareName" filterable :show-confirm="false"
              type="radio" @change="handleWarehouseChange"
            />
            <wd-select-picker
              v-model="formData.rackId" label="目标区域" label-width="150px" prop="formData.rackId"
              :columns="warehouseRackListTarget" placeholder="请选择目标货架" value-key="id" label-key="rackName" type="radio" :show-confirm="false"
              filterable @change="handleRackChange"
            />
            <!-- <wd-select-picker
              v-model="formData.locationId" label="目标库位" label-width="150px" prop="formData.locationId"
              :columns="rackLocationListTarget" placeholder="请选择目标库位" value-key="id" label-key="locationCode" type="radio" :show-confirm="false"
              filterable
            /> -->
            <wd-datetime-picker
              v-model="formData.actualDate" label="入库时间" type="datetime" placeholder="选择入库时间"
              label-width="150px" :default-value="defaulTimetValue" prop="formData.actualDate"
            />
            <wd-input
              v-model="formData.actualQuantity" label="入库数量" label-width="150px" prop="item.actualQuantity"
              placeholder="请输入入库数量"
            />

            <wd-input
              v-model="formData.unitPrice" label="单价" label-width="150px" prop="item.unitPrice"
              placeholder="请输入单价"
            />

            <wd-datetime-picker
              v-model="formData.productionDate" label="生产日期" type="datetime" placeholder="选择入生产日期"
              label-width="150px" :default-value="defaulTimetValue" :min-date="new Date(1900, 0, 1).getTime()" prop="formData.productionDate"
            />
          </view>
        </wd-card>
      </wd-cell-group>
      <view class="footer" style="margin-top: 30px;">
        <view class="" style="display: flex;justify-content: space-evenly;margin: 30px 0 20px 0;">
          <wd-button type="success" custom-class="custom-shadow" block @click="submitForm">
            提交
          </wd-button>
          <wd-button type="error" custom-class="custom-shadow" block @click="cancelForm">
            取消
          </wd-button>
        </view>
      </view>
    </wd-form>
  </view>
</template>

<style lang="scss" scoped>
//
</style>
